package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.CategoryService;
import com.sky.service.DishService;
import com.sky.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {


    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Resource
    private DishService dishService;
    @Resource
    private SetmealService setmealService;


    /**
     * 新增分类
     * @param categoryDTO
     */
    @Override
    public void saveCategory(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO,category);
        //分类状态默认为禁用状态0
        category.setStatus(StatusConstant.DISABLE);
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        category.setCreateUser(BaseContext.getCurrentId());
        category.setUpdateUser(BaseContext.getCurrentId());
        //保存到数据库
        //categoryMapper.insert(category);
        save(category);


    }

    /**
     * 分页查询
     * @param categoryPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(CategoryPageQueryDTO categoryPageQueryDTO) {
        // 创建分页对象
        Page<Category> page = new Page<>(categoryPageQueryDTO.getPage(), categoryPageQueryDTO.getPageSize());
        // 构建查询条件
//        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
//        if (categoryPageQueryDTO.getName() != null && !categoryPageQueryDTO.getName().isEmpty()) {
//            queryWrapper.like(Category::getName, categoryPageQueryDTO.getName());
//        }
//        if (categoryPageQueryDTO.getType() != null) {
//            queryWrapper.eq(Category::getType, categoryPageQueryDTO.getType());
//        }
//        // 添加排序条件
//        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getCreateTime);
//        // 执行分页查询
//        IPage<Category> resultPage = categoryMapper.selectPage(page, queryWrapper);
        LambdaQueryWrapper<Category> queryWrapper = Wrappers.<Category>lambdaQuery();
        // 添加查询条件
        Optional.ofNullable(categoryPageQueryDTO.getName()).ifPresent(name -> queryWrapper.like(Category::getName, name));
        Optional.ofNullable(categoryPageQueryDTO.getType()).ifPresent(type -> queryWrapper.eq(Category::getType, type));
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getCreateTime);
        page(page, queryWrapper);
        // 返回分页结果
        return new PageResult(page.getTotal(), page.getRecords());
    }

    /**
     *启用，禁用分类
     * @param
     */
    @Override
    public void setStatusByid(Long id, Integer status) {
       updateById(Category.builder().id(id).status(status).build());

    }

   //删除分类
    @Override
    public void removeByIdWithDish(Long id) {
        // 查询当前分类是否关联了菜品，如果关联了就抛出业务异常
//        LambdaQueryWrapper<Dish> dishQueryWrapper = new LambdaQueryWrapper<>();
//        dishQueryWrapper.eq(Dish::getCategoryId, id);
        long dishCount = dishService.count(Wrappers.<Dish>lambdaQuery().eq(Dish::getCategoryId, id).eq(Dish::getCategoryId, id));
        if (dishCount > 0) {
            // 当前分类下有菜品，不能删除
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
        }

        // 查询当前分类是否关联了套餐，如果关联了就抛出业务异常
//        LambdaQueryWrapper<Setmeal> setmealQueryWrapper = new LambdaQueryWrapper<>();
//        setmealQueryWrapper.eq(Setmeal::getCategoryId, id);
        //Long setmealCount = setmealMapper.selectCount(setmealQueryWrapper);
        long setmealCount = setmealService.count(Wrappers.<Setmeal>lambdaQuery().eq(Setmeal::getCategoryId, id));
        if (setmealCount > 0) {
            // 当前分类下有套餐，不能删除
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }

        // 删除分类数据
        categoryMapper.deleteById(id);
    }

    // 根据类型查询分类
    @Override
    public List<Category> listByType(Integer type) {
        LambdaQueryWrapper<Category> queryWrapper = Wrappers.<Category>lambdaQuery();
        // 1. 固定条件：status=1（启用状态）
        queryWrapper.eq(Category::getStatus, StatusConstant.ENABLE);
        // 2. 动态条件：type 只在非空时添加
        Optional.ofNullable(type).ifPresent(t -> queryWrapper.eq(Category::getType, t));
        // 3. 排序逻辑：sort 升序，create_time 降序
        queryWrapper.orderByAsc(Category::getSort)
                .orderByDesc(Category::getCreateTime);
        return list(queryWrapper);
    }




}

